#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import sys
import string
import json
import time
from Tools import connectMySQL

program_path = "/opt/wanalytics"

def countWap(argv=None):
    #执行并获得awk程序的返回值
    argv = sys.argv
    logfile = argv[1]
    cmd = "awk -f " + program_path + "/Tools/functions.awk -f" + program_path + "/scripts/log_wap.awk {0}".format(logfile)

    handle = os.popen(cmd)
    tmp = handle.read()
    tmp = json.loads(tmp)

    #统计结果项
    date = argv[2]
    pid = tmp.get("pid")
    pv = tmp.get("pvResults")
    uv = tmp.get("uvResults")
    vv = tmp.get("vvResults")

    #统计结果入表
    try:
        db = connectMySQL.connMySQL("stat")
    except MySQLdb.Error, e:
        print e
        resultStr = '{"status": "failed", "typeID": "%s", "code": "4001", "str": "connect database failed"}' % typeID
        return resultStr
    cursor = db.cursor()

    try:
        sql = "INSERT INTO `stat_day_main`(pid,date,pv,uv,vv) VALUES(%s,%s,%s,%s,%s)"
        param = (pid, date , pv, uv, vv)
        cursor.execute(sql, param) 
    except:
        sql = "UPDATE `stat_day_main` SET pv = %s,uv = %s,vv = %s WHERE pid=%s AND date=%s"
        param = (pv, uv, vv, pid, date)
        cursor.execute(sql, param) 
    finally:
         pass

    db.close()

if __name__ == '__main__':
    starttime = time.time()
    countWap();
    endtime = time.time()
    print "Run times:" + str(int((endtime - starttime)))  
